﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.XPath;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace Guolian.ProjectName.Infrastruct
{
    public static class SwaggerXmlHelper
    {
        public static readonly List<XPathNavigator> xmlNavigators = new List<XPathNavigator>();
        public static void IncludeXmlCommentsWithEnumDescription(this SwaggerGenOptions options, string xmlPath)
        {
            options.IncludeXmlComments(xmlPath);
            options.EnableAnnotations();
            options.SchemaFilter<EnumTypesSchemaFilter>();
            xmlNavigators.Add(new XPathDocument(xmlPath).CreateNavigator());
        }
        public static string? GetEnumComment(Type enumType, string enumValue)
        {
            foreach (var navigator in xmlNavigators)
            {
                var memberName = $"F:{enumType.FullName}.{enumValue}";
                var member = navigator.SelectSingleNode($"/doc/members/member[@name='{memberName}']");
                if (member == null) continue;

                return member.SelectSingleNode("summary")?.Value.Trim();
            }
            return null;
        }

    }
    public class EnumTypesSchemaFilter : ISchemaFilter
    {
        public void Apply(OpenApiSchema schema, SchemaFilterContext context)
        {
            if (!context.Type.IsEnum) return;

            var enumDescriptions = new List<string>();
            var enumType = context.Type;
            var underlyingType = Enum.GetUnderlyingType(enumType);

            foreach (var enumValue in Enum.GetValues(context.Type))
            {
                var name = Enum.GetName(context.Type, enumValue);
                if (name == null) continue;

                // 获取枚举值的 XML 注释
                var enumComment = SwaggerXmlHelper.GetEnumComment(enumType, name);
                var numericValue = Convert.ChangeType(enumValue, underlyingType);

                enumDescriptions.Add($"{numericValue}：{name}{(string.IsNullOrEmpty(enumComment) ? "" : $"，{enumComment}")}");
            }

            // 设置枚举描述
            schema.Description += $"<br />{string.Join("<br />", enumDescriptions)}";
        }
    }

}
